package org.finalministry.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class GuiMainActionListener implements ActionListener, ItemListener {

	private static final String ACTION_COMMANDS_PACKAGE = "org.finalministry.gui.action.";

	private GuiMain gui;

	public GuiMainActionListener(GuiMain gui) {
		this.gui = gui;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		performAction(e.getActionCommand());
	}

	/**
	 * Every action is implemented inside a IGuiAction class, extended from
	 * GuiActionBase.
	 * 
	 * @param actionCommand
	 */
	public void performAction(String actionCommand) {

		System.out.println(actionCommand);

		try {
			@SuppressWarnings("rawtypes")
			Class actionClass = Class.forName(ACTION_COMMANDS_PACKAGE + actionCommand.replaceAll(" ", "") + "Action");
			@SuppressWarnings("rawtypes")
			Class[] argTypes = { GuiMain.class };
			@SuppressWarnings({ "rawtypes", "unchecked" })
			Constructor constructor = actionClass.getDeclaredConstructor(argTypes);
			Object[] arguments = { gui };
			Object instance = constructor.newInstance(arguments);
			@SuppressWarnings("unchecked")
			Method performMethod = actionClass.getMethod("performAction", null);
			performMethod.invoke(instance, null);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	@Override
	public void itemStateChanged(ItemEvent e) {

		performAction(e.getItem().toString());

	}
}
